<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-add>
              <el-button @click="add">新增行</el-button>
            </template>
            <template v-slot:filter-remove>
              <el-button @click="remove" :disabled="canRemove"
                >删除行</el-button
              >
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :spanMethod="spanMethod"
                v-model:query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-requirementType="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}.requirementType`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: true,
                              message: '请输入需求类型',
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input
                      v-model="scope.row.requirementType"
                      :maxlength="64"
                      @blur="changeBlur($event, scope.row, scope.$index)"
                    ></el-input>
                  </el-form-item>
                </template>
                <template v-slot:col-importanceType="scope">
                  <el-form-item>
                    <SelectModel
                      v-model.lazy="scope.row.importanceType"
                      type-code="importance_type"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-requirement="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}.requirement`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: true,
                              message: '请输入需求描述',
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input
                      v-model="scope.row.requirement"
                      :maxlength="200"
                    ></el-input>
                  </el-form-item>
                </template>
              </PageTable>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="biddingParameterModify">
import {
  updateParameter,
  createParameter,
  getParameterById,
  getParameterAll,
} from '@/api/bidding.js'
import _ from 'lodash'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  orderId: {
    type: [String, Number],
  },
})
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '项目名称', value: 'name', type: 'input' },
    {
      value: 'projectType',
      type: 'select-model',
      code: 'project_type',
      label: '项目类别',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    projectType: [
      { required: true, message: '请选择项目类别', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    biddingParameterId: props.orderId,
  },
  list: [
    { type: 'slot', value: 'add' },
    { type: 'slot', value: 'remove' },
  ],
})

// 表格相关
const tableInfo = ref({
  data: [
    {
      requirementType: '',
      importanceType: '1',
      requirement: '',
      tableIndex: 0,
    },
  ],
  selections: [],

  fieldList: [
    {
      label: '需求类型',
      value: 'requirementType',
      type: 'slot',
      width: '300px',
    },
    {
      label: '重要程度',
      value: 'importanceType',
      type: 'slot',
      width: '200px',
    },
    {
      label: '需求描述',
      value: 'requirement',
      type: 'slot',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '新增行',
        event: addRow,
        show: true,
      },
      {
        label: '删除',
        event: removeRow,
        show: true,
      },
    ],
  },
})
const canRemove = computed(() => {
  return !tableInfo.value.selections.length
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      tableInfo.value.data.forEach((row, index) => {
        row.tableIndex = index
      })
    }
  },
  { deep: true }
)

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

function spanMethod({ row, column, rowIndex, columnIndex }) {
  let len = tableInfo.value.fieldList.length
  if (row.groupKey) {
    let afterIndexs = row.codeType === 2 || row.codeType === 3 ? [len + 1] : []

    let keys = new Array(len + 2)
    if (afterIndexs.length && afterIndexs.includes(columnIndex)) {
      keys[columnIndex] = 'groupKey'
    } else {
      keys = ['groupKey', 'requirementType']
    }
    // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
    return proxy.$fn.spanMethod(
      tableInfo.value.data,
      keys,
      rowIndex,
      columnIndex
    )
  }
}
function changeBlur(e, data, index) {
  let row = proxy.$fn.deepClone(data)
  if (row.groupKey) {
    tableInfo.value.data.forEach((item) => {
      if (item.groupKey === row.groupKey) {
        item.requirementType = row.requirementType
        item.groupKey = row.requirementType
      }
    })
  } else {
    tableInfo.value.data[index].groupKey = row.requirementType
  }

  tableInfo.value.data = _.sortBy(tableInfo.value.data, (item) => {
    if (item.groupKey) {
      return item.groupKey
    }
  })
}
function add() {
  tableInfo.value.data.push({
    requirementType: '',
    importanceType: '1',
    requirement: '',
  })
}
function remove() {
  let selections = proxy.$fn.deepClone(tableInfo.value.selections)
  let data = proxy.$fn.deepClone(tableInfo.value.data)
  let groupKey = []
  let tableIndexs = selections.map((item) => {
    if (item.groupKey) {
      groupKey.push(item.groupKey)
    }
    return item.tableIndex
  })
  if (groupKey.length) {
    data.forEach((item) => {
      if (groupKey.includes(item.groupKey)) {
        tableIndexs.push(item.tableIndex)
      }
    })
  }
  tableIndexs = Array.from(new Set(tableIndexs))
  let newData = data.filter((item) => !tableIndexs.includes(item.tableIndex))
  tableInfo.value.data = newData
  if (!tableInfo.value.data.length) {
    tableInfo.value.data.push({
      requirementType: '',
      importanceType: '1',
      requirement: '',
    })
  }
}
function addRow(row) {
  let data = proxy.$fn.deepClone(row)
  data.importanceType = '1'
  data.requirement = ''
  tableInfo.value.data.splice(row.tableIndex + 1, 0, data)
}
function removeRow(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  }
  if (!tableInfo.value.data.length) {
    tableInfo.value.data.push({
      requirementType: '',
      importanceType: '1',
      requirement: '',
    })
  }
}

function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let list = tableInfo.value.data.filter(
      (item) => !item.requirementType || !item.requirement
    )
    if (list.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '你还有未填写完的数据，请处理',
      })
      return
    }
    const api = props.orderId ? updateParameter : createParameter
    let data = formInfo.value.data
    data.mergeDetails = tableInfo.value.data
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function getMain() {
  getParameterById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
  getList()
}

function getList() {
  getParameterAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.length) {
        res.data.forEach((item) => {
          item.groupKey = item.requirementType
        })
      }
      tableInfo.value.data = res.data
    }
  })
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
  if (props.orderId) {
    getMain()
  }
})
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
</style>
